import hashlib

from rest_framework import serializers
from manage.models.system import User, Role, Permission, Menu, UserRole


# 权限表序列化器
class PermissionSerializer(serializers.ModelSerializer):
    # 设置虚拟属性: 子节点
    children = serializers.SerializerMethodField()
    class Meta:
        model = Permission
        fields = '__all__'
    # 虚拟属性初始化方法
    def get_children(self, obj):
        if obj.children.exists():
            return PermissionSerializer(obj.children.filter(status=True), many=True, context=self.context).data
        return []


# 角色表序列化器
class RoleSerializer(serializers.ModelSerializer):
    # 设置权限表序列化器
    # 名称必须和数据表模型类中保存外键关联数据的属性名称保持一致
    permission = PermissionSerializer(many=True, read_only=True)

    class Meta:
        model = Role
        fields = '__all__'


# 用户表序列化器
class UserSerializer(serializers.ModelSerializer):
    # 父级数据表序列化器
    # 名称必须和数据表模型类中保存外键关联数据的属性名保持一致
    role = RoleSerializer(many=True, read_only=True)
    # 额外字段, 为了接收前端传递的数据
    role_id=serializers.ListField(write_only=True)
    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {
            # 设置密码不显示
            'password': {
                'write_only': True
            }
        }
    # 重写create方法
    # def create(self, validated_data):
    #     print(validated_data,'validated_data')
    #     # 取出role_id, 列表类型
    #     role_id=validated_data.pop('role_id')
    #     # 执行新增操作
    #     # 实现密码加密
    #     validated_data['password']=hashlib.md5(validated_data.get('password').encode()).hexdigest()
    #     user=User.objects.create(**validated_data)
    #     for item in role_id:
    #         UserRole.objects.create(user=user, role_id=item)
    #     # 返回新增的用户对象
    #     return user


# 用户角色表序列化器
class UserRoleSerializer(serializers.ModelSerializer):
    # role = serializers.PrimaryKeyRelatedField(queryset=Role.objects.all())
    class Meta:
        model = UserRole
        fields = '__all__'

# 菜单表序列化器
class MenuSerializer(serializers.ModelSerializer):
    # 设置父表序列化器
    permission = PermissionSerializer(read_only=True)
    # 设置虚拟属性
    children = serializers.SerializerMethodField()
    # 父级id
    parent_id=serializers.CharField(write_only=True)
    class Meta:
        model = Menu
        fields = '__all__'

    # 虚拟属性初始化方法
    def get_children(self, obj):
        if obj.children.exists():
            return MenuSerializer(obj.children.filter(status=True), many=True, context=self.context).data
        return []
